<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表v-loading="listLoading"-->
    <el-table :data="tableDatas" v-loading="listLoading" @selection-change="handleSelectionChange"
      @row-dblclick="handleRowDblClick" highlight-current-row style="width: 100%">
      <!--多选框-->
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" width="400" label="序号"> </el-table-column>
      <el-table-column prop="dictName" label="数据字典名" width="400">
      </el-table-column>
      <el-table-column prop="sn" label="编号" width="400">
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-drawer title="数据字典明细" :visible.sync="drawerVisible" direction="rtl" size="50%">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px">
        <el-form :inline="true">
          <el-form-item>
            <el-button type="primary" @click="handleAddDetails">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-table :data="detailList" style="width: 100%">
        <el-table-column type="index" label="编号" width="200"></el-table-column>
        <el-table-column prop="itemName" label="明细名"></el-table-column>
        <el-table-column label="操作">
          <template scope="scope">
            <el-button size="small" @click="handleEditDetail(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelDetail(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>


    <!--添加或修改字典明细界面-->
    <!-- 新增：明细专属的新增/编辑弹窗 -->
    <el-dialog :title="detailTitle" :visible.sync="detailFormVisible" :close-on-click-modal="false">
      <el-form :model="detailForm" label-width="80px" :rules="detailFormRules" ref="detailForm">
        <!-- 明细名字段 -->
        <el-form-item label="明细名" prop="itemName">
          <el-input v-model="detailForm.itemName" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailFormVisible = false">取消</el-button>
        <el-button type="primary" @click="detailSubmit">提交</el-button>
      </div>
    </el-dialog>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" :disabled="this.sels.length === 0" @click="handlePatchDel">批量删除</el-button>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totals"
        style="float: right">
      </el-pagination>
    </el-col>

    <!--添加或修改界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="字典名" prop="dictName">
          <el-input v-model="saveForm.dictName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="字典编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      title: "",
      //1.分页查询相关数据
      totals: 0, //总记录条数
      currentPage: 1, //当前页,要传递到后台的
      pageSize: 5, //每页显示多少条
      tableDatas: [], //当前页数据
      listLoading: false,

      //2.高级查询相关数据
      keyword: "",

      //3.删除相关数据

      //4.批量删除相关数据
      sels: [], //存储多选记录

      //5.添加和修改相关数据
      saveFormVisible: false,
      saveForm: {
        id: null,
        dictName: null,
        sn: null
      },


      //6.添加和修改校验规则-表单项校验
      saveFormRules: {
        dictName: [
          { required: true, message: "请输入字典名称", trigger: "blur" },
        ],
        sn: [{ required: true, message: "请输入编号", trigger: "blur" }],
      },
      //7.抽屉相关数据
      drawerVisible: false,
      detailList: [], //数据字典明细列表
      currentDictId: null, //当前选中的数据字典ID
      detailFormVisible: false, // 明细弹窗显示状态
      detailTitle: "",          // 弹窗标题（新增/编辑）
      detailForm: {             // 明细表单数据
        id: null,               // 明细ID（编辑时用）
        dictId: null,           // 关联的主字典ID（必传，从currentDictId获取）
        itemName: null          // 明细名称
      },
      detailFormRules: {        // 明细表单校验规则
        itemName: [
          { required: true, message: "请输入明细名称", trigger: "blur" }
        ]
      }
    };

  },
  methods: {
    //1.分页查询相关方法
    //1.1.获取列表数据
    getTableData() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword,
      };
      this.listLoading = true; //显示加载圈!!!
      //分页查询
      this.$http.post("/dict", para).then((result) => {
        console.log(result);
        this.totals = result.data.total; //注意后端返回的是total,而不是totals!!!,可以打印result查看
        this.tableDatas = result.data.list;
        this.listLoading = false; //关闭加载圈!!!
      });
    },
    
    // 新增方法：处理行双击事件
    handleRowDblClick(row) {
      this.currentDictId = row.id;
      this.drawerVisible = true;
      this.loadDictDetails();
    },

    // 新增方法：加载数据字典明细
    loadDictDetails() {
      this.$http.get(`/dict/details/${this.currentDictId}`).then(res => {
        this.detailList = res.data.data;
      }).catch(err => {
        this.$message.error("加载明细数据失败");
        console.error(err);
      });
    },
    //1.2.选择第几页时触发
    handleCurrentChange(curentPage) {
      this.currentPage = curentPage;
      this.getTableData(); //获取列表数据
    },
    //1.3.选择每页显示记录条数时触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getTableData(); //获取列表数据
    },
    //2.高级查询相关方法
    keywordQuery() {
      this.currentPage = 1; //!!!

      this.getTableData(); //调用调用分页列表方法,因为关键字keyword已经进行了v-model的双向绑定!
    },
    handleDelDetail(row) {
      this.$confirm("此操作将永久删除该字典明细，是否继续？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .delete("/dict/delDetail/" + row.id)
            .then((res) => {
              console.log(res);
              if (res.data.success) {
                // 删除成功
                this.$message.success(res.data.msg);

                let lastPage = Math.ceil(this.totals / this.pageSize); // 向上取整，计算出当前的总页数，这个页数就是最后一页

                // 删除最后一页，只有一条数据，要返回上一页，并且最后一页不能是第一页
                if (
                  this.currentPage != 1 &&
                  this.totals % this.pageSize == 1 &&
                  this.currentPage == lastPage
                ) {
                  // 设置返回上一页
                  this.currentPage = this.currentPage - 1;
                }
                // 删除成功，重新查询列表
                this.loadDictDetails();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(() => {
              this.$message.error("网络异常，请稍后重试！【400/404/...】");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    //3.删除相关方法
    handleDel(row) {
      this.$confirm("此操作将永久删除该字典，是否继续？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .delete("/dict/" + row.id)
            .then((res) => {
              console.log(res);
              if (res.data.success) {
                // 删除成功
                this.$message.success(res.data.msg);

                let lastPage = Math.ceil(this.totals / this.pageSize); // 向上取整，计算出当前的总页数，这个页数就是最后一页

                // 删除最后一页，只有一条数据，要返回上一页，并且最后一页不能是第一页
                if (
                  this.currentPage != 1 &&
                  this.totals % this.pageSize == 1 &&
                  this.currentPage == lastPage
                ) {
                  // 设置返回上一页
                  this.currentPage = this.currentPage - 1;
                }
                // 删除成功，重新查询列表
                this.getTableData();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(() => {
              this.$message.error("网络异常，请稍后重试！【400/404/...】");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    //4.批量删除相关方法
    //4.1.选项改变时触发
    handleSelectionChange(val) {
      console.log(val);
      //传入的参数是选中的行的数据,行的数组,我们要从这个数组获取id,得到一个id数组[1,2,3,4]
      this.sels = val.map((u) => u.id); //!!!数组的map映射!!!
      console.log(this.sels);
    },
    //4.2.批量删除
    handlePatchDel() {
      this.$confirm("此操作将永久删除选中的字典，是否继续？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //获取当前用户的id
          this.$http
            .patch("/dict", this.sels)
            .then((res) => {
              if (res.data.success) {
                //删除成功
                this.$message.success(res.data.msg);
                //删除成功，重新查询列表
                this.getTableData();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(() => {
              this.$message.error("网络异常，请稍后重试！【400/404/...】");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    //5.添加和修改相关方法
    //5.1.点击添加弹出对话框
    handleAdd() {
      //1.清空form表单
      this.saveForm = {};
      //2.设置标题
      this.title = "新增";
      //3.弹出模态框
      this.saveFormVisible = true;
    },
    //5.2.点击修改弹出对话框
    handleEdit(row) {
      //1.设置标题
      this.title = "编辑";

      //2.将row对象拷贝给一个空对象,空对象赋值给saveForm.避免修改的时候影响行数据
      this.saveForm = Object.assign({}, row); //深拷贝!!!

      //3.弹出模态框
      this.saveFormVisible = true;
    },

    handleAddDetails() {
      this.detailForm = {
        dictId: this.currentDictId  // 关联当前双击的主字典ID
      };
      this.detailTitle = "新增数据字典明细"; // 设置弹窗标题
      this.detailFormVisible = true;       // 打开弹窗
    },
    handleEditDetail(row) {
      //2.将row对象拷贝给一个空对象,空对象赋值给saveForm.避免修改的时候影响行数据
      this.detailForm = Object.assign({}, row); //深拷贝!!!

      this.detailTitle = "新增数据字典明细"; // 设置弹窗标题
      this.detailFormVisible = true;
    },

    // 提交明细数据（弹窗的“提交”按钮触发）
    detailSubmit() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) { // 表单校验通过
          this.$http.put('/dict/details', this.detailForm).then(res => {
            if (res.data.success) {
              this.$message.success(res.data.msg);
              this.detailFormVisible = false; // 关闭弹窗
              this.loadDictDetails(); // 刷新明细列表
              if (this.saveForm.id == null) {
                this.totals++;
                this.currentPage = Math.ceil(this.totals / this.pageSize);
              }
              
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(err => {
            console.error(err);
            this.$message.error('网络异常，请稍后重试');
          });
        } else { // 表单校验失败
          this.$message.error('表单校验未通过，请检查输入');
          return false;
        }
      });
    },
    saveSubmit() {
      this.$refs["saveForm"].validate((valid) => {
        if (valid) {
          this.$http
            .put("/dict", this.saveForm)
            .then((res) => {
              if (res.data.success) {
                //1.提示操作成功
                this.$message.success(res.data.msg);

                //2.关闭对话框
                this.saveFormVisible = false;
                if (this.saveForm.id == null) {
                  this.totals++;
                  this.currentPage = Math.ceil(this.totals / this.pageSize);
                }
                this.getTableData();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(() => {
              this.$message.error("网络异常，请稍后重试！【400/404/...】");
            });
        } else {
          this.$message.error("表单校未通过！");
          return false;
        }
      });
    },
  },
  mounted() {
    this.getTableData();
  },
};
</script>

<style scoped></style>
